package cn.edu.nju.myweibo.json;

import java.util.ArrayList;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.edu.nju.myweibo.model.User;
import cn.edu.nju.myweibo.model.Weibo;

public class JsonParser {

	public static Iterator<Weibo> parseWeibo(String response) {

		ArrayList<Weibo> list = new ArrayList<Weibo>();

		try {

			JSONObject json = new JSONObject(response);
			JSONArray jsonArray = (JSONArray) json.get("statuses");

			for (int i = 0; i < jsonArray.length(); ++i) {

				JSONObject weibo_object = (JSONObject) jsonArray.get(i);

				long id = weibo_object.getLong("id");
				String text = weibo_object.getString("text");
				
				String picture = null;
				if (weibo_object.has("bmiddle_pic")) {
					picture = weibo_object.getString("bmiddle_pic");
				} else if (weibo_object.has("original_pic")) {
					picture = weibo_object.getString("original_pic");
				}

				JSONObject user_object = weibo_object.getJSONObject("user");
				User user = new User(user_object.getLong("id"), user_object.getString("screen_name"), user_object.getString("name"), user_object.getString("avatar_large"));

				Weibo weibo = new Weibo(id, text, picture, user, null);

				JSONObject retweeted_weibo_object = weibo_object;
				Weibo retweeted_weibo = weibo;
				
				while(retweeted_weibo_object.has("retweeted_status")) {
					
					retweeted_weibo_object = weibo_object.getJSONObject("retweeted_status");
					
					long retweeted_id = retweeted_weibo_object.getLong("id");
					String retweeted_text = retweeted_weibo_object.getString("text");
					
					String retweeted_picture = null;
					if (retweeted_weibo_object.has("bmiddle_pic")) {
						retweeted_picture = retweeted_weibo_object.getString("bmiddle_pic");
					} else if (retweeted_weibo_object.has("original_pic")) {
						retweeted_picture = retweeted_weibo_object.getString("original_pic");
					}

					JSONObject retweeted_user_object = retweeted_weibo_object.getJSONObject("user");
					User retweeted_user = new User(retweeted_user_object.getLong("id"), retweeted_user_object.getString("screen_name"), retweeted_user_object.getString("name"), retweeted_user_object.getString("avatar_large"));
					
					Weibo retweeted_status = new Weibo(retweeted_id, retweeted_text, retweeted_picture, retweeted_user, null);
					
					retweeted_weibo.setRetweeted_status(retweeted_status);
					retweeted_weibo = retweeted_status;
					
				}

				list.add(weibo);

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return list.iterator();

	}

}
